<template>
  <div class="companies-page">
    <div class="page-container">
      <!-- 搜索框 -->
      <div class="search-section">
        <el-input
          v-model="searchText"
          placeholder="搜索公司名称 / 行业 / 关键词"
          size="large"
          clearable
          class="search-input"
          @keyup.enter="handleSearch"
          @clear="handleSearch"
        >
          <template #prefix>
            <span style="font-size: 16px;">🔍</span>
          </template>
          <template #append>
            <el-button 
              type="primary" 
              size="large" 
              @click="handleSearch"
              :loading="esLoading"
            >搜索</el-button>
          </template>
        </el-input>
      </div>

      <!-- 筛选条件区域 -->
      <div class="filters-section">
        <div class="filter-row">
          <div class="filter-label">公司地点：</div>
          <div class="filter-options">
            <span
              v-for="city in cities"
              :key="city"
              class="filter-option"
              :class="{ active: selectedCity === city }"
              @click="selectedCity = city"
            >
              {{ city }}
            </span>
          </div>
        </div>
        <div class="filter-row">
          <div class="filter-label">行业类型：</div>
          <div class="filter-options">
            <span
              v-for="industry in industries"
              :key="industry"
              class="filter-option"
              :class="{ active: selectedIndustry === industry }"
              @click="selectedIndustry = industry"
            >
              {{ industry }}
            </span>
          </div>
        </div>
        <div class="filter-row">
          <div class="filter-label">融资阶段：</div>
          <div class="filter-options">
            <span
              v-for="stage in fundingStages"
              :key="stage"
              class="filter-option"
              :class="{ active: selectedFunding === stage }"
              @click="selectedFunding = stage"
            >
              {{ stage }}
            </span>
          </div>
        </div>
        <div class="filter-row">
          <div class="filter-label">公司规模：</div>
          <div class="filter-options">
            <span
              v-for="size in companySizes"
              :key="size"
              class="filter-option"
              :class="{ active: selectedSize === size }"
              @click="selectedSize = size"
            >
              {{ size }}
            </span>
          </div>
        </div>
        <div class="filter-actions">
          <el-button size="small" @click="clearFilters">清空筛选条件</el-button>
        </div>
      </div>

      <!-- 推荐栏 -->
      <div class="recommendation-bar">
        <div class="recommendation-left">
          <i class="star-icon">⭐</i>
          <span>根据求职期望推荐</span>
          <el-tag size="small" type="primary" class="skill-tag">Java</el-tag>
        </div>
        <div class="recommendation-right">
          <span class="default-recommend">默认推荐</span>
        </div>
      </div>

      <!-- 公司卡片网格 -->
      <div class="companies-grid">
        <div
          v-for="company in filteredCompanies"
          :key="company.id"
          class="company-card"
          @click="goToCompanyDetail(company.id)"
        >
          <div class="card-header">
            <img :src="company.logo" class="company-logo" :alt="company.name" />
            <div class="company-name">{{ company.name }}</div>
          </div>
          <div class="card-tags">
            <span class="tag">{{ company.status }}</span>
            <span class="tag">{{ company.industry }}</span>
          </div>
          <div class="card-hot-job">
            <span class="hot-label">热招</span>
            <div class="hot-job-info">
              <span class="hot-job-title">{{ company.hotJob.title }}</span>
              <span class="hot-job-salary">{{ company.hotJob.salary }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { esSearch } from '../../api/search'

export default {
  name: 'CompaniesView',
  data() {
    return {
      searchText: '',
      selectedCity: '北京',
      selectedIndustry: '不限',
      selectedFunding: '不限',
      selectedSize: '不限',
      useESSearch: true,       // 是否使用 ES 搜索
      esLoading: false,        // ES 搜索加载状态
      esSearchResults: [],     // ES 搜索结果
      esSearch: esSearch,      // ES 搜索方法
      cities: [
        '北京',
        '全国',
        '上海',
        '广州',
        '深圳',
        '杭州',
        '天津',
        '西安',
        '苏州',
        '武汉',
        '厦门',
        '长沙',
        '成都',
        '郑州',
        '重庆',
        '全部城市',
      ],
      industries: [
        '不限',
        '电子商务',
        '游戏',
        '社交网络与媒体',
        '广告营销',
        '大数据',
        '医疗健康',
        '生活服务(O2O)',
        '旅游',
        '分类信息',
        '人力资源服务',
        '企业服务',
        '信息安全',
        '智能硬件',
        '移动互联网',
        '互联网',
        '计算机软件',
        '通信/网络设备',
        '广告/公关/会展',
        '音乐/视频/阅读',
        '在线教育',
        '社交网络',
        '咨询',
        '工程施工',
        '汽车研发/制造',
        '其他行业',
        '互联网金融',
        '物流/仓储',
        '进出口贸易',
      ],
      fundingStages: [
        '不限',
        '未融资',
        '天使轮',
        'A轮',
        'B轮',
        'C轮',
        'D轮及以上',
        '已上市',
        '不需要融资',
      ],
      companySizes: [
        '不限',
        '0-20人',
        '20-99人',
        '100-499人',
        '500-999人',
        '1000-9999人',
        '10000人以上',
      ],
      companies: [
        {
          id: 'kuaishou',
          name: '快手',
          logo: '/upload/img_4.png',
          status: '已上市',
          industry: '社交网络与媒体',
          hotJob: {
            title: '客户端开发工程师',
            salary: '21-30K·16薪',
          },
        },
        {
          id: 'baidu',
          name: '百度',
          logo: '/upload/img.png',
          status: '已上市',
          industry: '互联网',
          hotJob: {
            title: '基础架构部研发工程师',
            salary: '30-60K·16薪',
          },
        },
        {
          id: 'xiaomi',
          name: '小米',
          logo: '/upload/img_3.png',
          status: '已上市',
          industry: '互联网',
          hotJob: {
            title: '高级Java开发工程师',
            salary: '20-40K·16薪',
          },
        },
        {
          id: 'huawei',
          name: '华为',
          logo: '/upload/img_2.png',
          status: '不需要融资',
          industry: '计算机软件',
          hotJob: {
            title: '软件开发(JS/java/pyt...)',
            salary: '25-45K·16薪',
          },
        },
        {
          id: 'alibaba',
          name: '阿里巴巴集团',
          logo: '/upload/img.png',
          status: '已上市',
          industry: '互联网',
          hotJob: {
            title: '高德JAVA高级工程师',
            salary: '25-50K·16薪',
          },
        },
        {
          id: 'jd',
          name: '京东集团',
          logo: '/upload/img_2.png',
          status: '已上市',
          industry: '电子商务',
          hotJob: {
            title: '后端开发工程师',
            salary: '30-60K·16薪',
          },
        },
        {
          id: 'boss',
          name: 'BOSS直聘',
          logo: '/upload/img_1.png',
          status: '已上市',
          industry: '人力资源服务',
          hotJob: {
            title: 'Java高级开发工程师',
            salary: '20-40K·16薪',
          },
        },
        {
          id: 'goodfuture',
          name: '好未来',
          logo: '/upload/img_3.png',
          status: '已上市',
          industry: '互联网',
          hotJob: {
            title: 'Java架构师',
            salary: '20-40K',
          },
        },
        {
          id: 'didi',
          name: '滴滴出行',
          logo: '/upload/img_4.png',
          status: 'D轮及以上',
          industry: '互联网',
          hotJob: {
            title: '高级java研发工程师',
            salary: '20-25K',
          },
        },
        {
          id: 'weibo',
          name: '微博',
          logo: '/upload/img.png',
          status: '已上市',
          industry: '互联网',
          hotJob: {
            title: 'JAVA高级开发工程师',
            salary: '20-40K·16薪',
          },
        },
        {
          id: 'tuyou',
          name: '途游游戏',
          logo: '/upload/img_1.png',
          status: '不需要融资',
          industry: '游戏',
          hotJob: {
            title: '游戏后端开发工程师',
            salary: '30-50K',
          },
        },
        {
          id: 'amap',
          name: '高德地图',
          logo: '/upload/img_2.png',
          status: '已上市',
          industry: '互联网',
          hotJob: {
            title: '阿里-高德-Java开发',
            salary: '45-70K·16薪',
          },
        },
      ],
    }
  },
  computed: {
    filteredCompanies() {
      // 如果使用了 ES 搜索，显示 ES 结果
      if (this.esSearchResults.length > 0) {
        return this.esSearchResults
      }
      
      let result = [...this.companies]
      
      // 根据搜索关键词过滤
      if (this.searchText && this.searchText.trim() && !this.useESSearch) {
        const keyword = this.searchText.trim().toLowerCase()
        result = result.filter(c => {
          return (
            c.name.toLowerCase().includes(keyword) ||
            c.industry.toLowerCase().includes(keyword) ||
            c.status.toLowerCase().includes(keyword) ||
            c.hotJob.title.toLowerCase().includes(keyword)
          )
        })
      }
      
      // 根据筛选条件过滤
      if (this.selectedCity !== '北京' && this.selectedCity !== '不限' && this.selectedCity !== '全部城市') {
        // 这里可以根据实际数据添加城市过滤逻辑
      }
      
      if (this.selectedIndustry !== '不限') {
        result = result.filter(c => c.industry === this.selectedIndustry)
      }
      
      if (this.selectedFunding !== '不限') {
        result = result.filter(c => c.status === this.selectedFunding)
      }
      
      return result
    },
  },
  methods: {
    async handleSearch() {
      // 如果有搜索关键词且启用 ES，使用 ES 搜索
      if (this.searchText.trim() && this.useESSearch) {
        await this.searchCompaniesFromES()
      }
    },
    
    // 使用 ES 搜索公司
    async searchCompaniesFromES() {
      this.esLoading = true
      try {
        const response = await this.esSearch({
          index: 'company_index',
          keyword: this.searchText.trim(),
          page: 1,
          size: 20
        })
        
        if (response.code === 200 && response.data?.docs) {
          // 将 ES 返回的数据转换为公司列表格式
          this.esSearchResults = response.data.docs.map(doc => ({
            id: doc.data.id || doc.id,  // 优先使用数据库ID，如果没有则使用ES文档ID
            ...doc.data,
            // 添加默认字段以兼容模板
            logo: doc.data.logo || '/upload/img.png',
            status: doc.data.is_verified ? '已上市' : '未认证',
            industry: doc.data.industry || '互联网',
            hotJob: {
              title: '查看职位',
              salary: '面议'
            }
          }))
          
          if (this.esSearchResults.length > 0) {
            this.$message.success(`找到 ${response.data.total} 家相关公司`)
          } else {
            this.$message.info('未找到相关公司')
            this.esSearchResults = []
          }
        } else {
          this.$message.warning('搜索服务暂时不可用')
          this.esSearchResults = []
        }
      } catch (error) {
        console.error('ES 搜索失败:', error)
        this.$message.error('搜索失败，请稍后重试')
        this.esSearchResults = []
      } finally {
        this.esLoading = false
      }
    },
    clearFilters() {
      this.selectedCity = '不限'
      this.selectedIndustry = '不限'
      this.selectedFunding = '不限'
      this.selectedSize = '不限'
      this.searchText = ''
      this.esSearchResults = []  // 清空 ES 搜索结果
    },
    goToCompanyDetail(companyId) {
      this.$router.push(`/company/${companyId}`)
    },
  },
}
</script>

<style scoped>
.companies-page {
  min-height: calc(100vh - 64px);
  background: #f5f5f5;
  padding: 24px 0;
}

.page-container {
  width: 80%;
  max-width: 1400px;
  margin: 0 auto;
}

/* 搜索框区域 */
.search-section {
  margin-bottom: 20px;
  padding: 20px 0;
}

.search-input {
  max-width: 800px;
  margin: 0 auto;
}

.search-input :deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #e5e5e5 inset;
}

.search-input :deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #00c293 inset;
}

.search-input :deep(.el-input.is-focus .el-input__wrapper) {
  box-shadow: 0 0 0 1px #00c293 inset;
}

/* 筛选条件区域 */
.filters-section {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  position: relative;
}

.filter-row {
  display: flex;
  align-items: flex-start;
  margin-bottom: 16px;
}

.filter-row:last-child {
  margin-bottom: 0;
}

.filter-label {
  font-weight: 600;
  color: #333;
  min-width: 100px;
  font-size: 14px;
  padding-top: 4px;
}

.filter-options {
  flex: 1;
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.filter-option {
  padding: 6px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  color: #666;
  transition: all 0.3s;
  border: 1px solid transparent;
}

.filter-option:hover {
  color: #00c293;
  background: #f0fffb;
}

.filter-option.active {
  color: #00c293;
  background: #f0fffb;
  border-color: #00c293;
  font-weight: 500;
}

.filter-actions {
  position: absolute;
  top: 20px;
  right: 20px;
}

/* 推荐栏 */
.recommendation-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #e6f7ff;
  padding: 12px 20px;
  border-radius: 6px;
  margin-bottom: 20px;
}

.recommendation-left {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #333;
}

.star-icon {
  font-size: 16px;
}

.skill-tag {
  margin-left: 4px;
}

.recommendation-right {
  font-size: 14px;
  color: #00c293;
  cursor: pointer;
}

.recommendation-right:hover {
  text-decoration: underline;
}

/* 公司卡片网格 */
.companies-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
}

.company-card {
  background: #fff;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  padding: 20px;
  cursor: pointer;
  transition: all 0.3s;
}

.company-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
  border-color: #00c293;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
}

.company-logo {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  object-fit: cover;
  border: 1px solid #f0f0f0;
}

.company-name {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  flex: 1;
}

.card-tags {
  display: flex;
  gap: 8px;
  margin-bottom: 12px;
  flex-wrap: wrap;
}

.tag {
  padding: 4px 10px;
  background: #f5f5f5;
  color: #999;
  border-radius: 12px;
  font-size: 12px;
}

.card-hot-job {
  padding-top: 12px;
  border-top: 1px dashed #e5e5e5;
}

.hot-label {
  display: inline-block;
  padding: 2px 8px;
  background: #fff4e6;
  color: #ff9800;
  border-radius: 3px;
  font-size: 12px;
  margin-right: 8px;
}

.hot-job-info {
  margin-top: 8px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.hot-job-title {
  font-size: 15px;
  color: #333;
  font-weight: 500;
  flex: 1;
}

.hot-job-salary {
  font-size: 15px;
  color: #ff4d4f;
  font-weight: 600;
  white-space: nowrap;
}
</style>
